import React, { useEffect, useRef, useState } from 'react';
import { Modal, message } from 'antd';
import { ProForm, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import services from '@/services/home';

const { fetchPositions, fetchScores } = services.PositionScore;

const PositionPage: React.FC = () => {
  const [filters, setFilters] = useState<any>(() => {
    const saved = localStorage.getItem('positionFilters');
    return saved ? JSON.parse(saved) : {
      positionCode: '',
      education: [],
      major: '',
      otherRequirements: '',
    };
  });

  const [tableData, setTableData] = useState<any[]>([]);
  const [tableColumns, setTableColumns] = useState<ProColumns<any>[]>([]);
  const [scoreData, setScoreData] = useState<any[]>([]);
  const [scoreColumns, setScoreColumns] = useState<ProColumns<any>[]>([]);
  const [scoreVisible, setScoreVisible] = useState(false);

  const actionRef = useRef<ActionType>();
  
  // 打开成绩弹窗
  const openScoreDialog = async (positionCode: string) => {
    try {
      const query = {
        province: '安徽省',
        city: '合肥市',
        date: '2025',
        positionCode,
      };
      const res = await fetchScores(query);
      setScoreData(res.data || []);
      const cols = (res.fractionNameKeyMap || []).map((col: any) => ({
        title: col.name || col,
        dataIndex: col.key || col,
        width: col.width || 120,
      }));
      setScoreColumns(cols);
      setScoreVisible(true);
    } catch (e) {
      message.error('获取成绩数据失败');
    }
  };

  // 请求职位数据
  const loadPositions = async (params = filters) => {
    try {
      const query = {
        province: '安徽省',
        city: '合肥市',
        date: '2025',
        ...params,
        education: params.education?.length ? params.education.join(',') : undefined,
      };
      console.log(services)
      const res = await fetchPositions(query);
      setTableData(res.data || []);

      // 动态表头
      const cols = (res.positionNameKeyMap || []).map((col: any) => ({
        title: col.name || col,
        dataIndex: col.key || col,
        width: col.width || 150,
        fixed: col.fixed || false,
        render: (text: any, record: any) => {
          if ((col.key || col) === 'positionCode') {
            return (
              <a onClick={() => openScoreDialog(record[col.key || col])}>
                {text}
              </a>
            );
          }
          return text;
        }
      }));
      setTableColumns(cols);
    } catch (e) {
      message.error('获取职位数据失败');
    }
  };

  // 初始加载
  useEffect(() => {
    loadPositions();
  }, []);

  // 提交筛选
  const onSubmit = async (values: any) => {
    setFilters(values);
    localStorage.setItem('positionFilters', JSON.stringify(values));
    await loadPositions(values);
  };

  // 重置
  const onReset = async () => {
    const resetValues = {
      positionCode: '',
      education: [],
      major: '',
      otherRequirements: '',
    };
    setFilters(resetValues);
    localStorage.setItem('positionFilters', JSON.stringify(resetValues));
    await loadPositions(resetValues);
  };

  return (
    <div>
      {/* 筛选表单 */}
      <ProForm
        layout="inline"
        initialValues={filters}
        onFinish={onSubmit}
        submitter={{
          searchConfig: {
            submitText: '提交',
            resetText: '重置',
          },
          onReset,
        }}
      >
        <ProFormText
          name="positionCode"
          label="职位代码"
          placeholder="请输入职位代码"
        />
        <ProFormSelect
          name="education"
          label="学历"
          mode="multiple"
          options={[
            { label: '本科', value: '本科' },
            { label: '专科', value: '专科' },
            { label: '高中', value: '高中' },
          ]}
          placeholder="请选择学历"
        />
        <ProFormText
          name="major"
          label="专业"
          placeholder="请输入专业"
        />
        <ProFormSelect
          name="otherRequirements"
          label="是否党员"
          options={[
            { label: '全部', value: '' },
            { label: '党员', value: '党员' },
          ]}
          placeholder="请选择"
        />
      </ProForm>

      {/* 职位表格 */}
      <ProTable
        rowKey="id"
        search={false}
        options={false}
        actionRef={actionRef}
        columns={tableColumns}
        dataSource={tableData}
        scroll={{ x: 'max-content', y: 'calc(100vh - 160px)' }}
        pagination={false}
      />

      {/* 成绩弹框 */}
      <Modal
        title="进面成绩"
        open={scoreVisible}
        onCancel={() => setScoreVisible(false)}
        footer={null}
        width="90%"
        style={{ top: 30 }}
      >
        <ProTable
          rowKey="id"
          search={false}
          options={false}
          columns={scoreColumns}
          dataSource={scoreData}
          scroll={{ x: 'max-content', y: 'calc(100vh - 200px)' }}
          pagination={false}
        />
      </Modal>
    </div>
  );
};

export default PositionPage;
